<script setup>
import { onMounted, ref } from "vue";
import { useInfoStore } from "@/stores/userInfo.js";
import { eidtInfoService, userInfoService } from "@/api/user";
import { ElMessage } from "element-plus";

const userInfo = ref({});
//调用接口获取用户信息
const getInfo = async () => {
  let result = await userInfoService();
  userInfo.value = result.data;
};
getInfo();

const rules = {
  nickname: [
    { required: true, message: "请输入用户昵称", trigger: "blur" },
    {
      pattern: /^\S{2,10}$/,
      message: "昵称必须是2-10位的非空字符串",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入用户邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "blur" },
  ],
};

//更新用户信息函数
const editInfo = async () => {
  if (userInfo.value.nickname == "" || userInfo.value.email == "") {
    ElMessage.error("请按规范填写");
  } else {
    await eidtInfoService(userInfo.value);
    ElMessage.success("更新成功");

    //更新store的数据
    useInfoStore().setInfo(userInfo.value);
  }
};
</script>

<template>
  <el-card class="page-container" style="max-width: 800px; margin: auto">
    <template #header>
      <div class="header">
        <span>基本资料</span>
      </div>
    </template>
    <el-row style="padding-left: 150px">
      <el-col :span="16">
        <el-form :model="userInfo" :rules="rules" label-width="100px" size="large">
          <el-form-item label="登录名称：">
            <el-input v-model="userInfo.account" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户昵称：" prop="nickname">
            <el-input v-model="userInfo.nickname"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱：" prop="email">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editInfo">提交更新</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
